<?php
/**
 * ****************************************************************************
 *  - TDMDownloads By TDM   - TEAM DEV MODULE FOR XOOPS
 *  - GNU Licence Copyright (c)  (www.xoops.org)
 *
 * La licence GNU GPL, garanti à l'utilisateur les droits suivants
 *
 * 1. La liberté d'exécuter le logiciel, pour n'importe quel usage,
 * 2. La liberté de l' étudier et de l'adapter à ses besoins,
 * 3. La liberté de redistribuer des copies,
 * 4. La liberté d'améliorer et de rendre publiques les modifications afin
 * que l'ensemble de la communauté en bénéficie.
 *
 * @copyright   http://www.tdmxoops.net
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
 * @author		TDM (G.Mage); TEAM DEV MODULE
 *
 * ****************************************************************************
 */

include 'admin_header.php';
//Affichage de la partie haute de l'administration de Xoops
xoops_cp_header();
//On recupere la valeur de l'argument op dans l'URL$
if (isset($_REQUEST['op'])) {
	$op = $_REQUEST['op'];
} else {
	$op = 'liste';
}
//paramètres:
// pour les images des catégories:
$uploaddir = XOOPS_ROOT_PATH . '/uploads/TDMDownloads/images/cats/';
$uploadurl = XOOPS_URL . '/uploads/TDMDownloads/images/cats/';
// pour les fichiers
$uploaddir_downloads = XOOPS_ROOT_PATH . '/uploads/TDMDownloads/downloads/';
$uploadurl_downloads = XOOPS_URL . '/uploads/TDMDownloads/downloads/';
/////////////

//appel des class
$downloadscat_Handler =& xoops_getModuleHandler('tdmdownloads_cat', 'TDMDownloads');
$downloads_Handler =& xoops_getModuleHandler('tdmdownloads_downloads', 'TDMDownloads');
$downloadsvotedata_Handler =& xoops_getModuleHandler('tdmdownloads_votedata', 'TDMDownloads');
$downloadsfielddata_Handler =& xoops_getModuleHandler('tdmdownloads_fielddata', 'TDMDownloads');
$downloadsbroken_Handler =& xoops_getModuleHandler('tdmdownloads_broken', 'TDMDownloads');

//appel du menu admin
if ( !is_readable(XOOPS_ROOT_PATH . "/Frameworks/art/functions.admin.php"))	{
    tdmdownloads_adminmenu(2, _MI_TDMDOWNLOADS_ADMENU2);
} else {
    include_once XOOPS_ROOT_PATH.'/Frameworks/art/functions.admin.php';
    loadModuleAdminMenu (2, _MI_TDMDOWNLOADS_ADMENU2);
}
// Sous-menu
echo '<div class="head" align="center">';
echo $op == 'new_cat' ? _AM_TDMDOWNLOADS_CAT_NEW : '<a href="category.php?op=new_cat">' . _AM_TDMDOWNLOADS_CAT_NEW . '</a>';
echo ' | ';
echo $op == 'liste' ? _AM_TDMDOWNLOADS_CAT_LIST : '<a href="category.php?op=liste">' . _AM_TDMDOWNLOADS_CAT_LIST . '</a>';
echo '</div><br>';

//Les valeurs de op qui vont permettre d'aller dans les differentes parties de la page
switch ($op) 
{
	// Vue liste
    case "liste": 
        $criteria = new CriteriaCompo();
        $criteria->setSort('weight ASC, title');
        $criteria->setOrder('ASC');
        $downloads_cat = $downloadscat_Handler->getall($criteria);
        $numrows = $downloadscat_Handler->getCount();
        //Affichage du tableau
        if ($numrows>0) {
			echo '<table width="100%" cellspacing="1" class="outer">';
			echo '<tr>';
			echo '<th align="left">' . _AM_TDMDOWNLOADS_FORMTITLE . '</th>';
            echo '<th align="center" width="10%">' . _AM_TDMDOWNLOADS_FORMIMG . '</th>';
            echo '<th align="center" width="5%">' . _AM_TDMDOWNLOADS_FORMWEIGHT . '</th>';
			echo '<th align="center" width="10%">' . _AM_TDMDOWNLOADS_FORMACTION . '</th>';			
			echo '</tr>';
			$class = 'odd';
            foreach (array_keys($downloads_cat) as $i) {               
                if ($downloads_cat[$i]->getVar('pid') == 0){                    
                    $downloadscat_cid = $downloads_cat[$i]->getVar('cid');
                    $downloadscat_imgurl = $downloads_cat[$i]->getVar('imgurl');
                    $downloads_title = $downloads_cat[$i]->getVar('title');
                    $downloadscat_weight = $downloads_cat[$i]->getVar('weight');
                    echo '<tr class="'.$class.'">';
                    echo '<td align="left"><a href="' . XOOPS_URL . '/modules/TDMDownloads/viewcat.php?cid=' . $downloadscat_cid . '">' . $downloads_title . '</a></td>';
                    echo '<td align="center" width="10%">';
                    echo '<img src="' . $uploadurl . $downloadscat_imgurl . '" alt="" title="" height="60">';
                    echo '</td>';
                    echo '<td align="center" width="5%">'.$downloadscat_weight.'</td>';
                    echo '<td align="center" width="10%">';
                    echo '<a href="category.php?op=view_cat&downloadscat_cid=' . $downloadscat_cid . '"><img src="../images/icon/view_mini.png" alt="'._AM_TDMDOWNLOADS_FORMDISPLAY.'" title="'._AM_TDMDOWNLOADS_FORMDISPLAY.'"></a> ';
                    echo '<a href="category.php?op=edit_cat&downloadscat_cid=' . $downloadscat_cid . '"><img src="../images/icon/edit_mini.gif" alt="'._AM_TDMDOWNLOADS_FORMEDIT.'" title="'._AM_TDMDOWNLOADS_FORMEDIT.'"></a> ';
                    echo '<a href="category.php?op=del_cat&downloadscat_cid=' . $downloadscat_cid . '"><img src="../images/icon/delete_mini.gif" alt="'._AM_TDMDOWNLOADS_FORMDEL.'" title="'._AM_TDMDOWNLOADS_FORMDEL.'"></a>';
                    echo '</td>';                    
                    echo '</tr>';
                    $class = ($class == 'even') ? 'odd' : 'even';
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('pid', $downloadscat_cid));
                    $criteria->setSort('weight ASC, title');
                    $criteria->setOrder('ASC');
                    $downloads_catchildren = $downloadscat_Handler->getall($criteria);
                    if (count($downloads_catchildren) != 0){
                        tdmdownloads_display_childrentree($downloads_cat[$i]->getVar('cid'),$downloads_catchildren, '', '', 'weight ASC, title', $class);
                    }
                }
            }
			echo '</table>';
		}
	break;
    
    // vue création
    case "new_cat":
        //Affichage du formulaire de création des catégories
    	$obj =& $downloadscat_Handler->create();
    	$form = $obj->getForm();
    	$form->display();
    break;
    
    // Pour éditer une catégorie
    case "edit_cat":
        //Affichage du formulaire de création des catégories
        $obj = $downloadscat_Handler->get($_REQUEST['downloadscat_cid']);
		$form = $obj->getForm();
		$form->display();
    break;
    
    // Pour supprimer une catégorie
    case "del_cat":
        global $xoopsModule;
		$obj =& $downloadscat_Handler->get($_REQUEST['downloadscat_cid']);
		if (isset($_REQUEST['ok']) && $_REQUEST['ok'] == 1) {
			if (!$GLOBALS['xoopsSecurity']->check()) {
				redirect_header('category.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
			}
            // supression des téléchargements de la catégorie
            $criteria = new CriteriaCompo();
            $criteria->add(new Criteria('cid', $_REQUEST['downloadscat_cid']));
            $downloads_arr = $downloads_Handler->getall($criteria);
			foreach (array_keys($downloads_arr) as $i) {
                // supression des votes
                $criteria_1 = new CriteriaCompo();
                $criteria_1->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                $downloads_votedata = $downloadsvotedata_Handler->getall($criteria_1);
                foreach (array_keys($downloads_votedata) as $j) {
                    $objvotedata =& $downloadsvotedata_Handler->get($downloads_votedata[$j]->getVar('ratingid'));
                    $downloadsvotedata_Handler->delete($objvotedata) or $objvotedata->getHtmlErrors();
                }
                // supression des rapports de fichier brisé
                $criteria_2 = new CriteriaCompo();
                $criteria_2->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                $downloads_broken = $downloadsbroken_Handler->getall($criteria_2);
                foreach (array_keys($downloads_broken) as $j) {
                    $objbroken =& $downloadsbroken_Handler->get($downloads_broken[$j]->getVar('reportid'));
                    $downloadsbroken_Handler->delete($objbroken ) or $objbroken ->getHtmlErrors();
                }
                // supression des data des champs sup.
                $criteria_3 = new CriteriaCompo();
                $criteria_3->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                $downloads_fielddata = $downloadsfielddata_Handler->getall($criteria_3);
                if ($downloadsfielddata_Handler->getCount( $criteria_3 ) > 0){
                    foreach (array_keys($downloads_fielddata) as $j) {
                        $objfielddata =& $downloadsfielddata_Handler->get($downloads_fielddata[$j]->getVar('iddata'));
                        $downloadsfielddata_Handler->delete($objfielddata) or $objvfielddata->getHtmlErrors();
                    }
                }
                // supression des commentaires
                if ($downloads_arr[$i]->getVar('comments') > 0){
                    xoops_comment_delete($xoopsModule->getVar('mid'), $downloads_arr[$i]->getVar('lid'));
                }
                //supression des tags
                if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
                    $tag_handler = xoops_getmodulehandler('link', 'tag');
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('tag_itemid', $downloads_arr[$i]->getVar('lid')));
                    $downloads_tags = $tag_handler->getall( $criteria );
                    if (count($downloads_tags) > 0){
                        foreach (array_keys($downloads_tags) as $j) {
                            $objtags =& $tag_handler->get($downloads_tags[$j]->getVar('tl_id'));
                            $tag_handler->delete($objtags) or $objtags->getHtmlErrors();
                        }
                    }
                }
                // supression du fichier
                // pour extraire le nom du fichier
                $urlfile = substr_replace($downloads_arr[$i]->getVar('url'),'',0,strlen($uploadurl_downloads));
                // chemin du fichier
                $urlfile = $uploaddir_downloads . $urlfile;
                if (is_file($urlfile)){		
					chmod($urlfile, 0777);
					unlink($urlfile);
				}
                // supression du téléchargment
				$objdownloads =& $downloads_Handler->get($downloads_arr[$i]->getVar('lid'));
                $downloads_Handler->delete($objdownloads) or $objdownloads->getHtmlErrors();
			}
            // supression des sous catégories avec leurs téléchargements            
            $downloadscat_arr = $downloadscat_Handler->getall();
            $mytree = new XoopsObjectTree($downloadscat_arr, 'cid', 'pid');
            $downloads_childcat=$mytree->getAllChild($_REQUEST['downloadscat_cid']);
            foreach (array_keys($downloads_childcat) as $i) {
                // supression de la catégorie
                $objchild =& $downloadscat_Handler->get($downloads_childcat[$i]->getVar('cid'));
                $downloadscat_Handler->delete($objchild) or $objchild->getHtmlErrors();
                // supression des téléchargements associés
                $criteria = new CriteriaCompo();
                $criteria->add(new Criteria('cid', $downloads_childcat[$i]->getVar('cid')));
                $downloads_arr = $downloads_Handler->getall( $criteria );
                foreach (array_keys($downloads_arr) as $i) {
                    // supression des votes
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                    $downloads_votedata = $downloadsvotedata_Handler->getall( $criteria );
                    foreach (array_keys($downloads_votedata) as $j) {
                        $objvotedata =& $downloadsvotedata_Handler->get($downloads_votedata[$j]->getVar('ratingid'));
                        $downloadsvotedata_Handler->delete($objvotedata) or $objvotedata->getHtmlErrors();
                    }
                    // supression des rapports de fichier brisé
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                    $downloads_broken = $downloadsbroken_Handler->getall( $criteria );
                    foreach (array_keys($downloads_broken) as $j) {
                        $objbroken =& $downloadsbroken_Handler->get($downloads_broken[$j]->getVar('reportid'));
                        $downloadsbroken_Handler->delete($objbroken ) or $objbroken ->getHtmlErrors();
                    }
                    // supression des data des champs sup.
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('lid', $downloads_arr[$i]->getVar('lid')));
                    $downloads_fielddata = $downloadsfielddata_Handler->getall( $criteria );
                    foreach (array_keys($downloads_fielddata) as $j) {
                        $objfielddata =& $downloadsfielddata_Handler->get($downloads_fielddata[$j]->getVar('iddata'));
                        $downloadsfielddata_Handler->delete($objfielddata) or $objvfielddata->getHtmlErrors();
                    }
                    // supression des commentaires
                    if ($downloads_arr[$i]->getVar('comments') > 0){
                        xoops_comment_delete($xoopsModule->getVar('mid'), $downloads_arr[$i]->getVar('lid'));
                    }
                    //supression des tags
                    if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
                        $tag_handler = xoops_getmodulehandler('link', 'tag');
                        $criteria = new CriteriaCompo();
                        $criteria->add(new Criteria('tag_itemid', $downloads_arr[$i]->getVar('lid')));
                        $downloads_tags = $tag_handler->getall( $criteria );
                        if (count($downloads_tags) > 0){
                            foreach (array_keys($downloads_tags) as $j) {
                                $objtags =& $tag_handler->get($downloads_tags[$j]->getVar('tl_id'));
                                $tag_handler->delete($objtags) or $objtags->getHtmlErrors();
                            }
                        }
                    }
                    // supression du fichier                        
                    $urlfile = substr_replace($downloads_arr[$i]->getVar('url'),'',0,strlen($uploadurl_downloads)); // pour extraire le nom du fichier                        
                    $urlfile = $uploaddir_downloads . $urlfile; // chemin du fichier
                    if (is_file($urlfile)){		
                        chmod($urlfile, 0777);
                        unlink($urlfile);
                    }
                    // supression du téléchargment
                    $objdownloads =& $downloads_Handler->get($downloads_arr[$i]->getVar('lid'));
                    $downloads_Handler->delete($objdownloads) or $objdownloads->getHtmlErrors();
                }
			}            
			if ($downloadscat_Handler->delete($obj)) {				
				redirect_header('category.php', 1, _AM_TDMDOWNLOADS_REDIRECT_DELOK);
			} else {
				echo $obj->getHtmlErrors();
			}
		} else {
            $message = '';
            $criteria = new CriteriaCompo();
            $criteria->add(new Criteria('cid', $_REQUEST['downloadscat_cid']));
            $downloads_arr = $downloads_Handler->getall( $criteria );
            if (count($downloads_arr) > 0) {
                $message .= _AM_TDMDOWNLOADS_DELDOWNLOADS .'<br>';
                foreach (array_keys($downloads_arr) as $i) {
                    $message .= '<span style="color : Red">' . $downloads_arr[$i]->getVar('title') . '</span><br>';
                }
            }            
            $downloadscat_arr = $downloadscat_Handler->getall();
            $mytree = new XoopsObjectTree($downloadscat_arr, 'cid', 'pid');
            $downloads_childcat=$mytree->getAllChild($_REQUEST['downloadscat_cid']);
			if (count($downloads_childcat) > 0) {
				$message .=_AM_TDMDOWNLOADS_DELSOUSCAT . ' <br><br>';
				foreach (array_keys($downloads_childcat) as $i) {
					$message .= '<b><span style="color : Red">' . $downloads_childcat[$i]->getVar('title') . '</span></b><br>';
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('cid', $downloads_childcat[$i]->getVar('cid')));
                    $downloads_arr = $downloads_Handler->getall( $criteria );
                    if (count($downloads_arr) > 0) {
                        $message .= _AM_TDMDOWNLOADS_DELDOWNLOADS .'<br>';
                        foreach (array_keys($downloads_arr) as $i) {
                            $message .= '<span style="color : Red">' . $downloads_arr[$i]->getVar('title') . '</span><br>';
                        }
                    }                    
				}
			}else{
				$message.='';
			}		
			xoops_confirm(array('ok' => 1, 'downloadscat_cid' => $_REQUEST['downloadscat_cid'], 'op' => 'del_cat'), $_SERVER['REQUEST_URI'], sprintf(_AM_TDMDOWNLOADS_FORMSUREDEL, $obj->getVar('title')) . '<br><br>' . $message);
		}

    break;
    
    // Pour voir les détails de la catégorie
    case "view_cat":
		$view_downloadscat = $downloadscat_Handler->get($_REQUEST['downloadscat_cid']);
		$criteria = new CriteriaCompo();
		$criteria->add(new Criteria('cid', $_REQUEST['downloadscat_cid']));
		$nb_downloads = $downloads_Handler->getCount($criteria);
		echo '<table width="100%" cellspacing="1" class="outer">';
		echo '<tr>';
		echo '<th align="center" colspan="2">' . $view_downloadscat->getVar('title') . '</th>';
		echo '</tr>';
		echo '<tr class="even">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMTEXT .' </td>';
		echo '<td>' . $view_downloadscat->getVar('description_main') . '</td>';
		echo '</tr>';
		echo '<tr class="odd">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMIMG .' </td>';
		echo '<td><img src="' . $uploadurl . $view_downloadscat->getVar('imgurl') . '" alt="" title="" height="60"></td>';
		echo '</tr>';
		echo '<tr class="even">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMWEIGHT .' </td>';
		echo '<td>' . $view_downloadscat->getVar('weight') . '</td>';
		echo '</tr>';
		echo '<tr class="odd">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_THEREIS .' </td>';
		echo '<td>' . $nb_downloads . ' ' . _AM_TDMDOWNLOADS_DOWNLOADSINCAT . '</td>';
		echo '</tr>';
		echo '<tr class="even">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMACTION .' </td>';
		echo '<td><a href="category.php?op=edit_cat&downloadscat_cid=' . $_REQUEST['downloadscat_cid'] . '"><img src="../images/icon/edit_mini.gif" alt="' . _AM_TDMDOWNLOADS_FORMEDIT .
        '" title="' . _AM_TDMDOWNLOADS_FORMEDIT . '"></a> <a href="category.php?op=del_cat&downloadscat_cid=' . $_REQUEST['downloadscat_cid'] . '">
        <img src="../images/icon/delete_mini.gif" alt="'. _AM_TDMDOWNLOADS_FORMDEL . '" title="' . _AM_TDMDOWNLOADS_FORMDEL . '"></a></td>';
		echo '</tr>';
		echo '</table>';
		echo '<br><br>';
		
	break;
    
    // Pour sauver une catégorie
	case "save_cat":
		if (!$GLOBALS['xoopsSecurity']->check()) {
           redirect_header('category.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
        }
        if (isset($_REQUEST['cid'])) {
           $obj =& $downloadscat_Handler->get($_REQUEST['cid']);
        } else {
           $obj =& $downloadscat_Handler->create();
        }
        $erreur = false;
        $message_erreur = '';
        // Récupération des variables:
        // Pour l'image
	    include_once XOOPS_ROOT_PATH.'/class/uploader.php';	    
        $uploader = new XoopsMediaUploader($uploaddir, array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/x-png', 'image/png'), $xoopsModuleConfig['maxuploadsize'], null, null);
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
			$uploader->setPrefix('downloads_') ;
			$uploader->fetchMedia($_POST['xoops_upload_file'][0]);
			if (!$uploader->upload()) {
				$errors = $uploader->getErrors();
				redirect_header("javascript:history.go(-1)",3, $errors);
			} else {
				$obj->setVar('imgurl', $uploader->getSavedFileName());
			}
		} else {
			$obj->setVar('imgurl', $_REQUEST['downloadscat_img']);
        }
        // Pour les autres variables
        $obj->setVar('pid', $_POST['pid']);
        $obj->setVar('title', $_POST['title']);
        $obj->setVar('description_main', $_POST['description_main']);
        $obj->setVar('weight', $_POST["weight"]);
        if (intval($_REQUEST['weight'])==0 && $_REQUEST['weight'] != '0'){
            $erreur=true;
            $message_erreur = _AM_TDMDOWNLOADS_ERREUR_WEIGHT . '<br>';
        }
        if (isset($_REQUEST['cid'])){
            if ($_REQUEST['cid'] == $_REQUEST['pid']){
                $erreur=true;
                $message_erreur .= _AM_TDMDOWNLOADS_ERREUR_CAT;
            }
        }
        if ($erreur==true){
            echo '<div class="errorMsg" style="text-align: left;">' . $message_erreur . '</div>';        
        }else{
            if ($downloadscat_Handler->insert($obj)) {
                if (!isset($_REQUEST['categorie_modified'])) {
                    $tags = array();
                    $tags['CATEGORY_NAME'] = $_POST['title'];
                    $tags['CATEGORY_URL'] = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewcat.php?cid=' . $obj->get_new_enreg();
                    $notification_handler =& xoops_gethandler('notification');
                    $notification_handler->triggerEvent('global', 0, 'new_category', $tags);
                }                
                redirect_header('category.php?op=liste', 1, _AM_TDMDOWNLOADS_REDIRECT_SAVE);
            }
            echo $obj->getHtmlErrors();
        }       
        $form =& $obj->getForm();
        $form->display();
	break;
}
//Affichage de la partie basse de l'administration de Xoops
xoops_cp_footer();
?>